package com.zhongli.devplatform.security.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.sun.org.apache.regexp.internal.RE;
import com.zhongli.devplatform.bean.GenericResponse;
import com.zhongli.devplatform.bean.Res;
import com.zhongli.devplatform.bean.ServiceError;
import com.zhongli.devplatform.constant.Consts;
import com.zhongli.devplatform.component.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author: WuXiCheng
 * @description: 确保在一次请求只通过一次filter，而不需要重复执行
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Value("${app.version}")
    private String version;

    @Value("${token.expirationMilliSeconds}")
    private long expirationMilliSeconds;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        final String requestTokenHeader = request.getHeader("Authorization");
        final String requestVersion = request.getHeader("version");

        //token为空直接放行
        if (StrUtil.isBlank(requestTokenHeader)) {
            filterChain.doFilter(request,response);
            response.setStatus(ServiceError.lgogin_AUTHORIZED.getCode());
            return;
        }
        String username = null;
        String jwtToken = null;
        //token异常处理
        if (StringUtils.hasLength(requestTokenHeader) && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                Claims claims = jwtTokenUtil.getClaimFromToken(jwtToken);
                username = claims.get("sub", String.class);
            } catch (JwtException e) {
                if (e instanceof ExpiredJwtException) {
                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    response.setStatus(ServiceError.lgogin_AUTHORIZED.getCode());
                    response.getWriter().write(JSON.toJSONString(new Res<>(401,"令牌已失效")));
                    return;
                } else if (e instanceof SignatureException) {
                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    response.setStatus(ServiceError.lgogin_AUTHORIZED.getCode());
                    response.getWriter().write(JSON.toJSONString(new Res<>(401,"签名异常")));
                    return;
                } else {
                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    response.setStatus(ServiceError.lgogin_AUTHORIZED.getCode());
                    response.getWriter().write(JSON.toJSONString(new Res<>(401,"令牌不正确")));
                    return;
                }
            }
        }
        if (StrUtil.isNotBlank(username) || SecurityContextHolder.getContext().getAuthentication() == null) {
            //获取缓存中的信息
            String redisToken = stringRedisTemplate.opsForValue().get(Consts.USER_TOKEN + username);
            if (StrUtil.isBlank(redisToken) || !redisToken.equals(jwtToken)){
                //token 不存在 返回错误信息
                response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                response.setStatus(ServiceError.lgogin_AUTHORIZED.getCode());
                response.getWriter().write(JSON.toJSONString(GenericResponse.response(ServiceError.lgogin_AUTHORIZED)));
                return;
            }
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null,userDetails.getAuthorities());
                usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
            //刷新token过期时间
            stringRedisTemplate.expire(Consts.USER_TOKEN + username, expirationMilliSeconds, TimeUnit.MILLISECONDS);
        }
        filterChain.doFilter(request,response);
    }
}
